package com.huateng.springcloud.jvm;

import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Object Pool
 *
 * @author Evan
 * @create 2021/6/28 11:22
 */
@Slf4j
public class HTObjectPool<E> {

    private static final int DEFAULT_MAX_COUNT = 100;

    //正在被使用对象的集合，已被同步
    private Set<E> activeSet = Collections.synchronizedSet(new HashSet<E>());

    //空闲的对象的集合，已被同步
    private Set<E> idleSet = Collections.synchronizedSet(new HashSet<E>());

    //最大对象数，默认为100
    private Integer maxCount = DEFAULT_MAX_COUNT;

    //线程等待监视器
    private final Object lock = new Object();

    public HTObjectPool(Integer maxCount){
        this.maxCount = maxCount;
    }

    /**
     * DESCRIPTION: 从对象池中取出对象
     * @author Evan
     * @date 2021/6/28
     * @param e
     * @return e
     */
    public synchronized <T> E takOutObject(Class<E> e) throws Exception {
        E obj = null;
        //如果有空闲对象，则从空闲对象集合中取一个返回
        if (idleSet.size() > 0){
            Iterator<E> iterator = idleSet.iterator();
            obj = iterator.next();
            log.info("ObjectPool复用老已有对象");
        }

        if (obj != null){
            idleSet.remove(obj);
            activeSet.add(obj);
        } else {

        }


        return null;
    }

}
